﻿using ImportMoudel;
using LightingServer;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace LightingPlatform.Web
{
    /// <summary>
    /// Summary description for LightingService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class LightingService : LightingBaseService
    {

        static LightingService()
        {
            string server = "127.0.0.1";
            string database = "zcdb";
            string uid = "root";
            string password = "";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
            LightingServerContext.ConnectionStrings = connectionString;
        }

        [WebMethod]
        public bool Commit(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return false;
            }

            LightingServerContext.WriteLine("Commit");
            return Import(bytes);
        }

        public bool Import(byte[] bytes)
        {
            try
            {
                ImportHandler handler = new ImportHandler();
                handler.Import(bytes);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取静态字典
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public byte[] DownloadResource()
        {
            try
            {
                return ResourceProvider.Res.ToByteArray();
            }
            catch (Exception ex)
            {
                return new byte[0];
            }
        }

        [WebMethod]
        public byte[] Login(string userName, string password)
        {

            User.Builder builder = new User.Builder();
            try
            {
                using (DbConnection conn = LightingServerContext.CreateConnection())
                {
                    using (DbCommand command = conn.CreateCommand())
                    {

                        conn.Open();
                        command.CommandText = "SELECT id, name, password, roleType FROM user WHERE name=@name AND password=@password;";

                        command.Parameters.AddRange(new MySqlParameter[]
                    {
                        new MySqlParameter()
                        {
                            ParameterName = "@name",
                            DbType = DbType.String,
                            Value = userName
                        },
                        new MySqlParameter()
                        {
                            ParameterName = "@password",
                            DbType = DbType.String,
                            Value = password
                        },
                    });

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            builder.SetId(reader["id"].ToString());
                            builder.SetName(reader["name"].ToString());
                            builder.SetPassword(reader["password"].ToString());
                            builder.SetRoleType(uint.Parse(reader["roleType"].ToString()));
                            break;
                        }
                    }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return builder.Build().ToByteArray();
        }

        [WebMethod]
        public byte[] LoadAllLables()
        {
            Res.Builder builder = new Res.Builder();
            try
            {
                LightingServerContext.WriteLine("LoadAllLables");
                using (DbConnection conn = LightingServerContext.CreateConnection())
                {
                    using (DbCommand command = conn.CreateCommand())
                    {
                        conn.Open();
                        command.CommandText = "SELECT DISTINCT lable FROM lighting ORDER BY lable;";

                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                string lable = reader["lable"] != null ? reader["lable"].ToString().Trim() : null;
                                if (!string.IsNullOrEmpty(lable))
                                {
                                    ResItem.Builder itemBuilder = new ResItem.Builder();
                                    itemBuilder.SetItemName(lable);
                                    builder.Res_List.Add(itemBuilder.Build());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return builder.Build().ToByteArray();
        }

        [WebMethod]
        public byte[] QueryLevel2(byte[] bytes)
        {
            LightingQueryService service = new LightingQueryService();
            Lightings lightings = service.QueryLevel2(QueryParameter2.ParseFrom(bytes));
            return lightings.ToByteArray();
        }

        [WebMethod]
        public byte[] QueryLevel3(byte[] bytes)
        {
            LightingQueryService service = new LightingQueryService();
            Lightings lightings = service.QueryLevel3(QueryParameter3.ParseFrom(bytes));
            return lightings.ToByteArray();
        }

        [WebMethod]
        public byte[] QueryLevel4(string id)
        {
            LightingQueryService service = new LightingQueryService();
            Lighting lighting = service.QueryLevel4(id);
            return lighting.ToByteArray();
        }

        [WebMethod]
        public byte[] QueryLevel5(string id)
        {
            LightingQueryService service = new LightingQueryService();
            Lighting lighting = service.QueryLevel5(id);
            return lighting.ToByteArray();
        }

        [WebMethod]
        public byte[] Query(byte[] bytes)
        {
            LightingQueryService service = new LightingQueryService();
            Lightings lightings = service.Query(LightingQuery.ParseFrom(bytes));
            return lightings.ToByteArray();
        }

        [WebMethod]
        public byte[] GetUsers()
        {
            LightingQueryService service = new LightingQueryService();
            Users users = service.GetUsers();
            return users.ToByteArray();
        }

        [WebMethod]
        public bool AddUser(byte[] bytes)
        {
            LightingQueryService service = new LightingQueryService();
            return service.AddUser(User.ParseFrom(bytes));
        }

        [WebMethod]
        public bool DeleteUser(string id)
        {
            LightingQueryService service = new LightingQueryService();
            return service.DeleteUser(id);
        }

        [WebMethod]
        public bool UpdateUser(byte[] bytes)
        {
            LightingQueryService service = new LightingQueryService();
            return service.UpdateUser(User.ParseFrom(bytes));
        }
    }
}
